#include <glib/gi18n.h>
#include <gtk/gtk.h>
#include "demo.h"

static GtkWidget* pbar;
static GtkWidget* pbar_pulse;
static int timer;


static gboolean progress_timeout (gpointer data)
{
    gdouble new_val;
    gchar *text;

    g_print("progress_timeout().....\n");

    gtk_progress_bar_pulse (GTK_PROGRESS_BAR (pbar_pulse));

    new_val = gtk_progress_bar_get_fraction (GTK_PROGRESS_BAR (pbar)) + 0.01;
    if (new_val > 1.00)
        new_val = 0.00;
    gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (pbar), new_val);

    text = g_strdup_printf ("%.0f%%", 100 * new_val);
    gtk_progress_bar_set_text(GTK_PROGRESS_BAR(pbar), text);
    g_free(text);

    return TRUE;        //continue to timeout
}

static void toggled_cb(GtkToggleButton *button, gpointer user_data)
{
    g_print("toggle_cb().....\n");

    if(gtk_toggle_button_get_active(button))
    {
        gtk_button_set_label(GTK_BUTTON(button), "Stop");
        
        if(timer == 0)
        {
            timer = g_timeout_add(100, (GSourceFunc)progress_timeout, button);
        }
    }
    else
    {
        gtk_button_set_label(GTK_BUTTON(button), "Run");

        if(timer != 0)
        {
            g_source_remove(timer);
            timer = 0;
        }
    }
}

static void destroy_cb(GtkToggleButton *button, gpointer user_data)
{
    g_print("destroy_cb().....\n");
    if(timer != 0)
    {
        g_source_remove(timer);
        timer = 0;
    }
}


void do_progressbar(GtkBox *parent)
{
    GtkWidget* frame;
    GtkWidget* vbox;
    // GtkWidget* pbar;
    // GtkWidget* pbar_pulse;
    GtkWidget* button;

    frame = gtk_frame_new("progressbar");
    gtk_container_set_border_width(GTK_CONTAINER(frame), 10);
    gtk_box_pack_start(parent, frame, TRUE, TRUE, 0);

    vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
    gtk_container_set_border_width(GTK_CONTAINER(vbox), 10);
    gtk_container_add(GTK_CONTAINER(frame), vbox);


    pbar = gtk_progress_bar_new();
    gtk_progress_bar_set_show_text(GTK_PROGRESS_BAR(pbar), TRUE);
    gtk_widget_set_halign (pbar, GTK_ALIGN_FILL);
    gtk_widget_set_valign (pbar, GTK_ALIGN_CENTER);
    gtk_box_pack_start(GTK_BOX(vbox), pbar, FALSE, FALSE, 5);

    pbar_pulse = gtk_progress_bar_new();
    gtk_widget_set_halign (pbar_pulse, GTK_ALIGN_FILL);
    gtk_widget_set_valign (pbar_pulse, GTK_ALIGN_CENTER);
    gtk_box_pack_start(GTK_BOX(vbox), pbar_pulse, FALSE, FALSE, 5);

    button = gtk_toggle_button_new_with_label("Run");
    gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 5);
    g_signal_connect(button, "toggled", G_CALLBACK(toggled_cb), button);
    g_signal_connect(button, "destroy", G_CALLBACK(destroy_cb), button);


    gtk_widget_show_all(GTK_WIDGET(parent));    
}